// stores/countdown.js
import { defineStore } from 'pinia'
import { ref, computed, onUnmounted } from 'vue'

export const useCountdownStore = defineStore('countdown', () => {
  const remainingTime = ref(0) // 剩余时间（秒）
  const targetTime = ref(null) // 目标时间戳
  const isRunning = ref(false)
  const timer = ref(null)
  
  const startTime = ref(0) // 开始时间
  
  // 格式化时间为 HH:MM:SS
  const formattedTime = computed(() => {
    const hours = Math.floor(remainingTime.value / 3600)
    const minutes = Math.floor((remainingTime.value % 3600) / 60)
    const secs = remainingTime.value % 60
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  })
  
  // 开始倒计时（参数：总秒数）
  function startCountdown(seconds) {
    stopCountdown()
	startTime.value = Date.now()
    remainingTime.value = seconds
    targetTime.value = Date.now() + seconds * 1000
    isRunning.value = true
    
    timer.value = setInterval(() => {
      const now = Date.now()
      const diff = Math.floor((targetTime.value - now) / 1000)
      
      if (diff <= 0) {
        remainingTime.value = 0
        stopCountdown()
        // 可以在这里触发倒计时结束事件
        uni.$emit('countdownFinished')
      } else {
        remainingTime.value = diff
      }
    }, 1000)
  }
  
  // 暂停倒计时
  function pauseCountdown() {
    if (timer.value) {
      clearInterval(timer.value)
      timer.value = null
      isRunning.value = false
    }
  }
  
  // 停止倒计时
  function stopCountdown() {
    pauseCountdown()
	// startTime.value = 0
    remainingTime.value = 0
    targetTime.value = null
  }
  
  // 恢复倒计时
  function resumeCountdown() {
    if (targetTime.value && !isRunning.value) {
      startCountdown(Math.floor((targetTime.value - Date.now()) / 1000))
    }
  }
  
  // 组件卸载时清理
  onUnmounted(() => {
    stopCountdown()
  })
  
  return { 
    remainingTime, 
    formattedTime, 
	startTime,
    isRunning,
    startCountdown, 
    pauseCountdown, 
    stopCountdown,
    resumeCountdown
  }
})